// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database()

// 云函数入口函数
exports.main = async(event, context) => {
  let t1 = event.startDate + " " + event.startTime
  let t2 = event.endDate + " " + event.endTime
  let start = new Date(t1.replace(/-/g, "/"))
  let end = new Date(t2.replace(/-/g, "/"))

  if (!event.addressId) {
    const $ = db.command.aggregate
    return await db.collection("registration").aggregate()
      .match({
        address_id: db.command.in(event.addressIds),
        time: {
          $gte: start.getTime(),
          $lte: end.getTime()
        }
      }).lookup({
        from: 'address',
        localField: "address_id",
        foreignField: "_id",
        as: "address"
      }).end()
  } else {
    return await db.collection("registration").aggregate()
      .match({
        address_id: event.addressId,
        time: db.command.gte(start.getTime()).and(db.command.lte(end.getTime())),
        type: event.typeIndex == '0' ? db.command.neq('') : event.typeIndex,
        is_cough: event.coughIndex == '0' ? db.command.neq('') : event.coughIndex,
        temperature: event.feverIndex == '0' ? db.command.gt(0) : event.feverIndex == '1' ? db.command.gte(37.2) : db.command.lt(37.2),
        car_id: event.carId == '' ? db.command.neq(' ') : event.carId,
        name: event.name == '' ? db.command.neq('') : event.name
      }).lookup({
        from: 'address',
        localField: "address_id",
        foreignField: "_id",
        as: "address"
      }).end()
  }
}